<?php
/**
@author 
@copyright 2008
 */
require_once ($_SERVER['DOCUMENT_ROOT']."/conf/conf.php");
// Load JsHttpRequest backend.
require_once ROOT_DIR."/js/JsHttpRequest/JsHttpRequest.php";
// Create main library object. You MUST specify page encoding!
$JsHttpRequest =& new JsHttpRequest("UTF-8");
// Store resulting data in $_RESULT array (will appear in req.responseJs).
/**
 * CONFIGURATION
 */
define ("DIRECT_ACCESS", true);
$smarty=init_smarty("");
$user = new User($db);
$module= array(
	'incl_dir' => '/',
	'tmpl_dir' => '/'
);
$tmpl_dir="templates/";
$table_ratings = $db->pfx."ratings";
$table_games = $db->pfx."flash_games";
/**
 * Если указано действия, то дальнейшее управление передается "вилке" выбора
 */
if (isset($_REQUEST['action']))
	$action = $_REQUEST['action'];
/**
 * В случае отсутствия явного указания действия Ajax прекратит работу и выдаст алерт
 */
else die("Ошибка! Не указано действие!");
/**
 *	START
 */
switch($action)
{
	case 'recurse':
		if(isset($_REQUEST['parent']) and $_REQUEST['parent']!='')
		{
			$parent=intval($_REQUEST['parent']);
			$categories=recurse($parent,1,0,1,1);
			//print $parent;
			$smarty->assign("categories",$categories);
			switch($_REQUEST['type'])
			{
				case 'select':
					$output = $smarty->fetch("templates/other/select_cat.html");
					break;
				case 'checkbox':
					$output = $smarty->fetch("templates/other/select_cat_checkbox.html");
					break;
				case 'radio':
					$output = $smarty->fetch("templates/other/select_cat_radio.html");
					break;
			}
			
		}
		$GLOBALS['_RESULT']=array('output'=>$output);
	break;
	case 'get_menu':
		if(isset($_REQUEST['parent']) and $_REQUEST['parent']!='')
		{
			$parent=intval($_REQUEST['parent']);
			$page = new Page($parent);
			$submenu = $page->getMenu($parent,1);
			$smarty->assign("submenu",$submenu);
			$output = $smarty->fetch("templates/other/submenu.html");
		}
		$GLOBALS['_RESULT']=array('output'=>$output);
	break;
	case 'addAdress':
		if(isset($_REQUEST['parent']) and $_REQUEST['parent']!='')
		{
		}
	break;
	case 'rating':
		$ok = 0;
		$output_message = array();
		if(isset($_REQUEST['obj_id']) and intval($_REQUEST['obj_id']) != 0 and isset($_REQUEST['module']) and strval($_REQUEST['module']) != '' and isset($_REQUEST['grade']) and intval($_REQUEST['grade']) != 0)
		{
			$item_id = intval($_REQUEST['obj_id']);
			$module = mysql_real_escape_string($_REQUEST['module']);
			$grade = intval($_REQUEST['grade']);
			if(!$user->user_id)
			{
				$is_user_vote = $db->fetch_one("SELECT id FROM $table_ratings WHERE obj_id = '".$item_id."' AND module = '$module' AND user_id = '0' AND ip = '".$_SESSION['site']['ip']."'");
			}
			else
			{
				$is_user_vote = $db->fetch_one("SELECT id FROM $table_ratings WHERE obj_id = '".$item_id."' AND module = 'flash' AND user_id = '$user->user_id'");
			}
			if($is_user_vote != false and intval($is_user_vote['id']) != 0)
			{
				$output_message[] = "Извините, но вы уже голосовали";
			}
			else
			{
				$new_vote = array(
					'obj_id' => $item_id,
					'module' => $module,
					'user_id' => $user->user_id,
					'ip' => $_SESSION[$user->pfx]['ip'],
					'grade' => $grade,
					'time' => time()
				);
				$res_ins_new_vote = $db->insert($table_ratings,$new_vote);
				if($res_ins_new_vote != false)
				{
					$rating = $db->fetch_one("SELECT AVG(grade) AS rating, COUNT(*) AS votes FROM $table_ratings WHERE obj_id = '$item_id' AND module = '$module'");
					$new_rating = array(
						'rating' => $rating['rating'],
						'votes' => $rating['votes']
					);
					$res_upd_game_stat = $db->update($table_games,$new_rating,"WHERE id = '$item_id'");
					if($res_upd_game_stat != false)
					{
						$rating['obj_id'] = $item_id;
						$rating['module'] = "flash";
						$rating['rating_text'] = uni_word_end("балл",($rating['rating']/1),array("ов","а",""),1);
						$rating['votes_text'] = uni_word_end("оцен",intval($rating['votes']),array("ок","ки","ка"),1);
						$rating['uservote'] = $new_vote;
						$smarty->assign("rating",$rating);
						$ok = 1;$output_message[] = $smarty->fetch("templates/other/rating.inc.html");
					}
					else
					{
						$ok = 1;$output_message[] = "Спасибо за ваш голос! Данные будут обновлены чуть позднее";
					}
				}
				else
				{
					$output_message[] = "Извините, возникла трудность при попытке добавить ваш голос в нашу БД. Админ уже извещен и уволен.";
				}
			}
		}
		else
		{
			$output_message[] = "Извините, голосование пока не доступно";
		}
		$GLOBALS['_RESULT']=array('ok'=>$ok,'output'=>implode("<br />",$output_message));
	break;
	/** //TODO: Slider - получает следущие элементы и отдает данные в jQuery
	**/
	case 'Slider':
		$from = intval($_REQUEST['from']);	// оффсет для выборки
		$navigation = array(
			'prev_link' =>false,
			'next_link' =>true,
			'from' => 0
		);
		switch($_REQUEST['module'])
		{
			case 'flash':
				// основные переменные
				$obj = new FlashGameWizard($db);
				$mod_dir = 'index';
				$template="gameroller.inc.html";			// шаблон для подмены
				$per_page = 1;					// сколько фотографий попытаться показать за раз
				$lim_from = $from * $per_page;	// lim_from - оффсет для выборки с использованием LIMIT
				if(isset($_REQUEST['where_array']) and is_array($_REQUEST['where_array']) and !empty($_REQUEST['where_array']))
				{
					$additionalWhereClause = "";
					$where_array = $_REQUEST['where_array'];
					foreach($where_array as $field => $value)
					{
						$additionalWhereClause = " AND ".mysql_real_escape_string($field)." = '".mysql_real_escape_string($value)."'";
					}
				}
			    // теперь получим фотки из него с учетом оффсета и постраничной навигации
				/** START 	Consultants */
				// ID разделов, посвященных работе - 11 и 28
				$obj_id = $obj->db->fetch_array("SELECT SQL_CALC_FOUND_ROWS $obj->id FROM $obj->table WHERE image = '1' AND file = '1' AND status = '2' $additionalWhereClause ORDER BY rating DESC,votes DESC, hits DESC, $obj->id DESC LIMIT $lim_from,$per_page",MYSQL_ASSOC);
				//print "SELECT SQL_CALC_FOUND_ROWS $obj->id FROM $obj->table WHERE image = '1' AND file = '1' AND status = '2' $additionalWhereClause ORDER BY rating DESC,votes DESC LIMIT $from,$per_page";
				if(!empty($obj_id))
				{
					$obj_qnty = $obj->db->fetch_one(QUANTITY);
					$game = $obj->getFullInfoById($obj_id[0][$obj->id]);
					if($game != false)
					{
						if($from > 0) $navigation['prev_link'] = true;
						else $navigation['prev_link'] = false;
						if($from < intval($obj_qnty[0]-1)) $navigation['next_link'] = true;
						else $navigation['next_link'] = false;
						$navigation['from'] = $from;
						$smarty->assign("game",$game);
					}
				}
				/** END 	Consultants */
				// парсим шаблон в переменную
				$output = $smarty->fetch('modules/'.$mod_dir.'/'.$tmpl_dir.$template);
				// Вуаля! Отсылаем результат:-)
				$GLOBALS['_RESULT']=array('output'=>$output,'navigation'=>$navigation);
				break;
		}
	break;
}
/**
 *	END
 */
?>